"use client"

import { Button } from "@/components/ui/button"
import { useState, useEffect } from "react"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, Plus } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { format } from "date-fns"

interface Sample {
  id: string
  userId: string
  sampleNumber: string
  sampleName: string
  sampleType: string
  testingUnit: string
  mixedNumber: string | null
  samplingNumber: string | null
  operator: string | null
  operationTime: Date | null
}

type SampleStatus = "all" | "unassigned" | "mixed-only" | "completed"

export default function SampleManagement() {
  // 示例数据：包含三种状态的样品，并且一个抽检编号对应两个混合编号
  const [samples, setSamples] = useState<Sample[]>([
    // 未生成任何编号的样品
    {
      id: "1",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851408...",
      sampleName: "测试名称",
      sampleType: "测试类型",
      testingUnit: "测试送检单位",
      mixedNumber: null,
      samplingNumber: null,
      operator: null,
      operationTime: null,
    },
    {
      id: "2",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851409...",
      sampleName: "测试2",
      sampleType: "土壤样品",
      testingUnit: "测试送检单位2",
      mixedNumber: null,
      samplingNumber: null,
      operator: null,
      operationTime: null,
    },
    {
      id: "3",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851410...",
      sampleName: "测试3",
      sampleType: "水质样品",
      testingUnit: "测试送检单位3",
      mixedNumber: null,
      samplingNumber: null,
      operator: null,
      operationTime: null,
    },
    // 只生成了混合编号的样品 - MX001
    {
      id: "4",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851411...",
      sampleName: "测试4",
      sampleType: "空气样品",
      testingUnit: "测试送检单位4",
      mixedNumber: "MX001",
      samplingNumber: null,
      operator: "张三",
      operationTime: new Date(2025, 6, 15, 10, 30),
    },
    {
      id: "5",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851412...",
      sampleName: "测试5",
      sampleType: "土壤样品",
      testingUnit: "测试送检单位5",
      mixedNumber: "MX001",
      samplingNumber: null,
      operator: "张三",
      operationTime: new Date(2025, 6, 15, 10, 30),
    },
    {
      id: "6",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851413...",
      sampleName: "测试6",
      sampleType: "水质样品",
      testingUnit: "测试送检单位6",
      mixedNumber: "MX001",
      samplingNumber: null,
      operator: "张三",
      operationTime: new Date(2025, 6, 15, 10, 30),
    },
    // 只生成了混合编号的样品 - MX002
    {
      id: "7",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851414...",
      sampleName: "测试7",
      sampleType: "空气样品",
      testingUnit: "测试送检单位7",
      mixedNumber: "MX002",
      samplingNumber: null,
      operator: "李四",
      operationTime: new Date(2025, 6, 16, 14, 45),
    },
    {
      id: "8",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851415...",
      sampleName: "测试8",
      sampleType: "土壤样品",
      testingUnit: "测试送检单位8",
      mixedNumber: "MX002",
      samplingNumber: null,
      operator: "李四",
      operationTime: new Date(2025, 6, 16, 14, 45),
    },
    {
      id: "9",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851416...",
      sampleName: "测试9",
      sampleType: "水质样品",
      testingUnit: "测试送检单位9",
      mixedNumber: "MX002",
      samplingNumber: null,
      operator: "李四",
      operationTime: new Date(2025, 6, 16, 14, 45),
    },
    // 一个抽检编号(SP001)对应两个混合编号(MX003和MX004)
    {
      id: "10",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851417...",
      sampleName: "测试10",
      sampleType: "空气样品",
      testingUnit: "测试送检单位10",
      mixedNumber: "MX003",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
    {
      id: "11",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851418...",
      sampleName: "测试11",
      sampleType: "土壤样品",
      testingUnit: "测试送检单位11",
      mixedNumber: "MX003",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
    {
      id: "12",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851419...",
      sampleName: "测试12",
      sampleType: "水质样品",
      testingUnit: "测试送检单位12",
      mixedNumber: "MX003",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
    {
      id: "13",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851420...",
      sampleName: "测试13",
      sampleType: "空气样品",
      testingUnit: "测试送检单位13",
      mixedNumber: "MX004",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
    {
      id: "14",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851421...",
      sampleName: "测试14",
      sampleType: "土壤样品",
      testingUnit: "测试送检单位14",
      mixedNumber: "MX004",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
    {
      id: "15",
      userId: "I2IAAAQIHCGA...",
      sampleNumber: "337924851422...",
      sampleName: "测试15",
      sampleType: "水质样品",
      testingUnit: "测试送检单位15",
      mixedNumber: "MX004",
      samplingNumber: "SP001",
      operator: "王五",
      operationTime: new Date(2025, 6, 18, 9, 15),
    },
  ])

  const [selectedSamples, setSelectedSamples] = useState<string[]>([])
  const [selectedMixedGroups, setSelectedMixedGroups] = useState<string[]>([])
  const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null)
  const [lastSelectedType, setLastSelectedType] = useState<"sample" | "mixed" | null>(null)
  const [isShiftPressed, setIsShiftPressed] = useState(false)
  const [searchTerm, setSearchTerm] = useState("")
  const [startDate, setStartDate] = useState<Date | undefined>(undefined)
  const [endDate, setEndDate] = useState<Date | undefined>(undefined)
  const [statusFilter, setStatusFilter] = useState<SampleStatus>("all")
  const [mixedGroupSize, setMixedGroupSize] = useState(3)
  const [showMixedDialog, setShowMixedDialog] = useState(false)
  const [showSamplingDialog, setShowSamplingDialog] = useState(false)

  // 监听Shift键的按下和释放
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Shift") {
        setIsShiftPressed(true)
      }
    }

    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === "Shift") {
        setIsShiftPressed(false)
      }
    }

    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)

    return () => {
      window.removeEventListener("keydown", handleKeyDown)
      window.removeEventListener("keyup", handleKeyUp)
    }
  }, [])

  // 处理单个样品选择（未生成编号的样品）
  const handleSelectSample = (sampleId: string, checked: boolean, index: number) => {
    if (isShiftPressed && lastSelectedIndex !== null && lastSelectedType === "sample") {
      // Shift键范围选择逻辑
      const unassignedSamples = filteredSamples.filter((s) => !s.mixedNumber)
      const currentSampleIndex = unassignedSamples.findIndex((s) => s.id === sampleId)
      const lastSampleIndex = lastSelectedIndex

      if (currentSampleIndex !== -1 && lastSampleIndex !== -1) {
        const start = Math.min(lastSampleIndex, currentSampleIndex)
        const end = Math.max(lastSampleIndex, currentSampleIndex)

        // 获取范围内的所有样品ID
        const rangeIds = unassignedSamples.slice(start, end + 1).map((s) => s.id)

        // 添加范围内所有样品到选中列表
        const newSelected = [...new Set([...selectedSamples, ...rangeIds])]
        setSelectedSamples(newSelected)
      }
    } else {
      // 普通单选逻辑
      if (checked) {
        setSelectedSamples([...selectedSamples, sampleId])
      } else {
        setSelectedSamples(selectedSamples.filter((id) => id !== sampleId))
      }
      // 更新最后选择的索引和类型
      const unassignedSamples = filteredSamples.filter((s) => !s.mixedNumber)
      const currentIndex = unassignedSamples.findIndex((s) => s.id === sampleId)
      setLastSelectedIndex(currentIndex)
      setLastSelectedType("sample")
    }
  }

  // 处理混合编号组选择（只生成混合编号的样品）
  const handleSelectMixedGroup = (mixedNumber: string, checked: boolean, index: number) => {
    if (isShiftPressed && lastSelectedIndex !== null && lastSelectedType === "mixed") {
      // 获取所有混合编号组
      const mixedGroups = [
        ...new Set(filteredSamples.filter((s) => s.mixedNumber && !s.samplingNumber).map((s) => s.mixedNumber)),
      ]

      const currentMixedIndex = mixedGroups.indexOf(mixedNumber)
      const lastMixedIndex = lastSelectedIndex

      if (currentMixedIndex !== -1 && lastMixedIndex !== -1) {
        const start = Math.min(lastMixedIndex, currentMixedIndex)
        const end = Math.max(lastMixedIndex, currentMixedIndex)

        // 获取范围内的所有混合编号
        const rangeMixedNumbers = mixedGroups.slice(start, end + 1).filter(Boolean) as string[]

        // 添加范围内所有混合编号到选中列表
        const newSelected = [...new Set([...selectedMixedGroups, ...rangeMixedNumbers])]
        setSelectedMixedGroups(newSelected)
      }
    } else {
      // 普通单选逻辑
      if (checked) {
        setSelectedMixedGroups([...selectedMixedGroups, mixedNumber])
      } else {
        setSelectedMixedGroups(selectedMixedGroups.filter((id) => id !== mixedNumber))
      }
      // 更新最后选择的索引和类型
      const mixedGroups = [
        ...new Set(filteredSamples.filter((s) => s.mixedNumber && !s.samplingNumber).map((s) => s.mixedNumber)),
      ]
      const currentIndex = mixedGroups.indexOf(mixedNumber)
      setLastSelectedIndex(currentIndex)
      setLastSelectedType("mixed")
    }
  }

  // 生成混合编号
  const generateMixedNumbers = () => {
    if (selectedSamples.length === 0) {
      alert("请先选择要生成混合编号的样品")
      return
    }

    const unassignedSamples = samples.filter((s) => selectedSamples.includes(s.id) && !s.mixedNumber)
    if (unassignedSamples.length === 0) {
      alert("所选样品中没有未分配编号的样品")
      return
    }

    const newSamples = [...samples]
    const groupCount = Math.ceil(unassignedSamples.length / mixedGroupSize)

    for (let i = 0; i < groupCount; i++) {
      const mixedNumber = `MX${String(i + 1).padStart(3, "0")}`
      const startIndex = i * mixedGroupSize
      const endIndex = Math.min(startIndex + mixedGroupSize, unassignedSamples.length)

      for (let j = startIndex; j < endIndex; j++) {
        const sampleIndex = newSamples.findIndex((s) => s.id === unassignedSamples[j].id)
        if (sampleIndex !== -1) {
          newSamples[sampleIndex] = {
            ...newSamples[sampleIndex],
            mixedNumber,
            operator: "系统自动",
            operationTime: new Date(),
          }
        }
      }
    }

    setSamples(newSamples)
    setSelectedSamples([])
    setShowMixedDialog(false)
    alert(`成功生成 ${groupCount} 个混合编号`)
  }

  // 生成抽检编号
  const generateSamplingNumbers = () => {
    if (selectedMixedGroups.length === 0) {
      alert("请先选择要生成抽检编号的混合编号组")
      return
    }

    const newSamples = [...samples]
    const samplingNumber = `SP${String(1).padStart(3, "0")}`

    selectedMixedGroups.forEach((mixedNumber) => {
      const sampleIndices = newSamples
          .map((s, index) => ({ sample: s, index }))
          .filter(({ sample }) => sample.mixedNumber === mixedNumber && !sample.samplingNumber)
          .map(({ index }) => index)

      sampleIndices.forEach((index) => {
        newSamples[index] = {
          ...newSamples[index],
          samplingNumber,
          operator: "系统自动",
          operationTime: new Date(),
        }
      })
    })

    setSamples(newSamples)
    setSelectedMixedGroups([])
    setShowSamplingDialog(false)
    alert(`成功生成抽检编号 ${samplingNumber}`)
  }

  const getMixedNumberColor = (mixedNumber: string) => {
    const colors = [
      "bg-blue-100 text-blue-800",
      "bg-green-100 text-green-800",
      "bg-purple-100 text-purple-800",
      "bg-orange-100 text-orange-800",
    ]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return colors[index]
  }

  const getSamplingNumberColor = (samplingNumber: string) => {
    const colors = ["bg-red-100 text-red-800", "bg-indigo-100 text-indigo-800", "bg-pink-100 text-pink-800"]
    const index = Number.parseInt(samplingNumber.replace("SP", "")) % colors.length
    return colors[index]
  }

  // 获取行的背景色（根据样品状态）
  const getRowBackgroundColor = (sample: Sample, isSelected: boolean) => {
    if (isSelected) return "bg-blue-50"

    if (!sample.mixedNumber) {
      return "bg-gray-50" // 未分配编号
    } else if (sample.mixedNumber && !sample.samplingNumber) {
      return "bg-yellow-50" // 只有混合编号
    } else {
      return "bg-green-50" // 完整编号
    }
  }

  // 获取混合编号单元格的边框样式
  const getMixedCellBorderStyle = (mixedNumber: string) => {
    const baseStyle = "border-l-4"
    const colors = ["border-blue-300", "border-green-300", "border-purple-300", "border-orange-300"]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return `${baseStyle} ${colors[index]}`
  }

  // 过滤样品
  const filteredSamples = samples.filter((sample) => {
    // 搜索条件
    const matchesSearch =
        searchTerm === "" ||
        sample.sampleNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        sample.sampleName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        sample.userId.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (sample.operator && sample.operator.toLowerCase().includes(searchTerm.toLowerCase()))

    // 日期范围条件
    let matchesDateRange = true
    if (startDate && sample.operationTime) {
      matchesDateRange = sample.operationTime >= startDate
    }
    if (endDate && sample.operationTime) {
      matchesDateRange = matchesDateRange && sample.operationTime <= endDate
    }

    // 状态筛选条件
    let matchesStatus = true
    if (statusFilter === "unassigned") {
      matchesStatus = !sample.mixedNumber
    } else if (statusFilter === "mixed-only") {
      matchesStatus = !!sample.mixedNumber && !sample.samplingNumber
    } else if (statusFilter === "completed") {
      matchesStatus = !!sample.mixedNumber && !!sample.samplingNumber
    }

    return matchesSearch && matchesDateRange && matchesStatus
  })

  // 统计信息
  const mixedGroups = [...new Set(samples.filter((s) => s.mixedNumber).map((s) => s.mixedNumber))].length
  const samplingGroups = [...new Set(samples.filter((s) => s.samplingNumber).map((s) => s.samplingNumber))].length
  const unassignedSamples = samples.filter((s) => !s.mixedNumber).length
  const onlyMixedSamples = samples.filter((s) => s.mixedNumber && !s.samplingNumber).length

  return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-bold">样品管理系统</h1>
          <div className="flex gap-2">
            <Dialog open={showMixedDialog} onOpenChange={setShowMixedDialog}>
              <DialogTrigger asChild>
                <Button variant="outline" size="sm" disabled={selectedSamples.length === 0}>
                  <Plus className="w-4 h-4 mr-2" />
                  生成混合编号
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>生成混合编号</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="groupSize">每组样品数量</Label>
                    <Select value={mixedGroupSize.toString()} onValueChange={(value) => setMixedGroupSize(Number(value))}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="2">2个样品一组</SelectItem>
                        <SelectItem value="3">3个样品一组</SelectItem>
                        <SelectItem value="4">4个样品一组</SelectItem>
                        <SelectItem value="5">5个样品一组</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="text-sm text-muted-foreground">
                    已选择 {selectedSamples.length} 个未分配样品，将生成{" "}
                    {Math.ceil(selectedSamples.length / mixedGroupSize)} 个混合编号组
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button variant="outline" onClick={() => setShowMixedDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={generateMixedNumbers}>确认生成</Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>

            <Dialog open={showSamplingDialog} onOpenChange={setShowSamplingDialog}>
              <DialogTrigger asChild>
                <Button variant="outline" size="sm" disabled={selectedMixedGroups.length === 0}>
                  <Plus className="w-4 h-4 mr-2" />
                  生成抽检编号
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>生成抽检编号</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div className="text-sm text-muted-foreground">
                    已选择 {selectedMixedGroups.length} 个混合编号组，将生成 1 个抽检编号
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button variant="outline" onClick={() => setShowSamplingDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={generateSamplingNumbers}>确认生成</Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        {/* 搜索和筛选条件 */}
        <div className="flex gap-4 items-center">
          <Input
              placeholder="搜索样品..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-64"
          />

          <Select value={statusFilter} onValueChange={(value: SampleStatus) => setStatusFilter(value)}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="选择状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="unassigned">未分配</SelectItem>
              <SelectItem value="mixed-only">已混合编号但未抽检编号</SelectItem>
              <SelectItem value="completed">已抽检编号</SelectItem>
            </SelectContent>
          </Select>

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" size="icon">
                <Calendar className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <div className="p-3 border-b">
                <div className="text-sm font-medium">操作时间范围</div>
              </div>
              <div className="p-3 flex flex-col gap-2">
                <div>
                  <div className="text-xs mb-1">开始日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={startDate}
                      onSelect={setStartDate}
                      className="border rounded-md"
                  />
                </div>
                <div>
                  <div className="text-xs mb-1">结束日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={endDate}
                      onSelect={setEndDate}
                      className="border rounded-md"
                  />
                </div>
                <div className="flex justify-end">
                  <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setStartDate(undefined)
                        setEndDate(undefined)
                      }}
                  >
                    重置
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">总样品数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{samples.length}</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-gray-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">未分配样品</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{unassignedSamples}</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-yellow-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">仅混合编号</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{onlyMixedSamples}</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-blue-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">混合编号组数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{mixedGroups}</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-green-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">抽检编号组数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{samplingGroups}</div>
            </CardContent>
          </Card>
        </div>

        {/* 样品表格 - 完全禁用hover效果 */}
        <style jsx global>{`
          /* 完全禁用表格行的hover效果 */
          .disable-hover-effect tbody tr:hover {
            background-color: inherit !important;
          }

          /* 保持原始背景色 */
          .bg-gray-50 {
            background-color: rgb(249, 250, 251) !important;
          }

          .bg-yellow-50 {
            background-color: rgb(254, 252, 232) !important;
          }

          .bg-green-50 {
            background-color: rgb(240, 253, 244) !important;
          }

          .bg-blue-50 {
            background-color: rgb(239, 246, 255) !important;
          }
        `}</style>

        <Card>
          <CardContent className="p-0">
            <Table className="disable-hover-effect">
              <TableHeader>
                <TableRow className="bg-gray-100">
                  <TableHead className="w-12">选择</TableHead>
                  <TableHead>抽检编号</TableHead>
                  <TableHead>混合编号</TableHead>
                  <TableHead>样品编号</TableHead>
                  <TableHead>用户ID</TableHead>
                  <TableHead>样品名称</TableHead>
                  <TableHead>样品类型</TableHead>
                  <TableHead>送检单位</TableHead>
                  <TableHead>操作人</TableHead>
                  <TableHead>操作时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredSamples.map((sample, index) => {
                  // 情况1：未生成任何编号 - 显示单个样品的勾选框
                  if (!sample.mixedNumber && !sample.samplingNumber) {
                    const isSelected = selectedSamples.includes(sample.id)

                    return (
                        <TableRow key={sample.id} className={getRowBackgroundColor(sample, isSelected)}>
                          <TableCell>
                            <Checkbox
                                checked={isSelected}
                                onCheckedChange={(checked) => handleSelectSample(sample.id, checked as boolean, index)}
                            />
                          </TableCell>
                          <TableCell>-</TableCell>
                          <TableCell>-</TableCell>
                          <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                          <TableCell className="font-mono text-sm">{sample.userId}</TableCell>
                          <TableCell>{sample.sampleName}</TableCell>
                          <TableCell>{sample.sampleType}</TableCell>
                          <TableCell>{sample.testingUnit}</TableCell>
                          <TableCell>{sample.operator || "-"}</TableCell>
                          <TableCell>
                            {sample.operationTime ? format(sample.operationTime, "yyyy-MM-dd HH:mm") : "-"}
                          </TableCell>
                        </TableRow>
                    )
                  }

                  // 情况2：只生成了混合编号 - 每个混合编号组显示一个勾选框
                  if (sample.mixedNumber && !sample.samplingNumber) {
                    const mixedNumber = sample.mixedNumber as string
                    const mixedRowSpan = filteredSamples.filter((s) => s.mixedNumber === mixedNumber).length
                    const mixedFirstIndex = filteredSamples.findIndex((s) => s.mixedNumber === mixedNumber)
                    const showMixedCell = index === mixedFirstIndex
                    const showCheckbox = index === mixedFirstIndex
                    const isSelected = selectedMixedGroups.includes(mixedNumber)

                    return (
                        <TableRow key={sample.id} className={getRowBackgroundColor(sample, isSelected)}>
                          <TableCell>
                            {showCheckbox && (
                                <Checkbox
                                    checked={isSelected}
                                    onCheckedChange={(checked) =>
                                        handleSelectMixedGroup(mixedNumber, checked as boolean, index)
                                    }
                                />
                            )}
                          </TableCell>
                          <TableCell>-</TableCell>
                          {showMixedCell && (
                              <TableCell
                                  rowSpan={mixedRowSpan}
                                  className={`align-middle ${getMixedCellBorderStyle(mixedNumber)}`}
                              >
                                <Badge variant="secondary" className={getMixedNumberColor(mixedNumber)}>
                                  {mixedNumber}
                                </Badge>
                              </TableCell>
                          )}
                          <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                          <TableCell className="font-mono text-sm">{sample.userId}</TableCell>
                          <TableCell>{sample.sampleName}</TableCell>
                          <TableCell>{sample.sampleType}</TableCell>
                          <TableCell>{sample.testingUnit}</TableCell>
                          <TableCell>{sample.operator || "-"}</TableCell>
                          <TableCell>
                            {sample.operationTime ? format(sample.operationTime, "yyyy-MM-dd HH:mm") : "-"}
                          </TableCell>
                        </TableRow>
                    )
                  }

                  // 情况3：已生成抽检编号 - 不显示勾选框
                  if (sample.mixedNumber && sample.samplingNumber) {
                    const samplingNumber = sample.samplingNumber as string
                    const mixedNumber = sample.mixedNumber as string

                    // 计算抽检编号的rowspan - 一个抽检编号可能对应多个混合编号
                    const samplingRowSpan = filteredSamples.filter((s) => s.samplingNumber === samplingNumber).length
                    const samplingFirstIndex = filteredSamples.findIndex((s) => s.samplingNumber === samplingNumber)
                    const showSamplingCell = index === samplingFirstIndex

                    // 计算混合编号的rowspan
                    const mixedRowSpan = filteredSamples.filter((s) => s.mixedNumber === mixedNumber).length
                    const mixedFirstIndex = filteredSamples.findIndex((s) => s.mixedNumber === mixedNumber)
                    const showMixedCell = index === mixedFirstIndex

                    return (
                        <TableRow key={sample.id} className={getRowBackgroundColor(sample, false)}>
                          <TableCell>-</TableCell>
                          {showSamplingCell && (
                              <TableCell rowSpan={samplingRowSpan} className="align-middle border-l-4 border-green-300">
                                <Badge variant="secondary" className={getSamplingNumberColor(samplingNumber)}>
                                  {samplingNumber}
                                </Badge>
                              </TableCell>
                          )}
                          {showMixedCell && (
                              <TableCell
                                  rowSpan={mixedRowSpan}
                                  className={`align-middle ${getMixedCellBorderStyle(mixedNumber)}`}
                              >
                                <Badge variant="secondary" className={getMixedNumberColor(mixedNumber)}>
                                  {mixedNumber}
                                </Badge>
                              </TableCell>
                          )}
                          <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                          <TableCell className="font-mono text-sm">{sample.userId}</TableCell>
                          <TableCell>{sample.sampleName}</TableCell>
                          <TableCell>{sample.sampleType}</TableCell>
                          <TableCell>{sample.testingUnit}</TableCell>
                          <TableCell>{sample.operator || "-"}</TableCell>
                          <TableCell>
                            {sample.operationTime ? format(sample.operationTime, "yyyy-MM-dd HH:mm") : "-"}
                          </TableCell>
                        </TableRow>
                    )
                  }

                  return null
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* 选择状态说明 */}
        <Card>
          <CardContent className="p-4">
            <div className="text-sm space-y-2">
              <div className="flex items-center gap-4">
                <strong>状态颜色说明：</strong>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 bg-gray-50 border border-gray-200"></div>
                  <span>未分配编号</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 bg-yellow-50 border border-gray-200"></div>
                  <span>仅混合编号</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 bg-green-50 border border-gray-200"></div>
                  <span>完整编号</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 bg-blue-50 border border-gray-200"></div>
                  <span>已选择</span>
                </div>
              </div>
              <div>
                <strong>选择操作说明：</strong>
                <span className="ml-2">按住Shift键点击可以进行范围选择</span>
              </div>
              <div className="mt-2">
              <span className="text-muted-foreground">
                已选择样品：{selectedSamples.length} 个 | 已选择混合组：{selectedMixedGroups.length} 个
              </span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
  )
}
